﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Ship.DaDa
{
    /// <summary>
    /// 达达配送，公共方法
    /// </summary>
    public class Function
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="ht"></param>
        /// <returns></returns>
        public static string ToJson(object ht)
        {
            return JsonConvert.SerializeObject(ht);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Hashtable DeJson(string json)
        {
            return JsonConvert.DeserializeObject<Hashtable>(json);
        }

        /// <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string GetMD5(string data)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hashByte = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
            StringBuilder sb = new StringBuilder();
            foreach (byte item in hashByte)
                sb.Append(item.ToString("x").PadLeft(2, '0'));
            return sb.ToString().ToUpper();
        }

        /// <summary>
        /// 获取签名字符串
        /// </summary>
        /// <param name="ht">发送的键值对</param>
        /// <returns></returns>
        public static string GetSign(SortedDictionary<string, object> sortArr)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in sortArr)
            {
                sb.Append(item.Key + item.Value);
            }
            return GetMD5(Config.app_secret + sb.ToString() + Config.app_secret);
        }

        /// <summary>
        /// 当前时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimestamp()
        {
            return ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds)
                .ToString().Substring(0, 10);
        }

        /// <summary>
        /// 简单的签名字符串
        /// </summary>
        /// <param name="ht"></param>
        /// <returns></returns>
        public static string GetSignatureForCallback(Hashtable ht)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(ht.Keys);
            akeys.Sort();
            for (int i = 0; i < akeys.Count; i++)
            {
                string key = akeys[i].ToString();
                sb.Append(key + ht[key]);
            }
            return GetMD5(sb.ToString());
        }
    }
}